<template>
  <div style="flex: 5" v-if="bomInfos != null && bomInfos.length > 0">
    <div
      style="
        display: flex;
        justify-content: left;
        margin-bottom: 8px;
        margin-left: 15px;
      "
    >
      <el-button type="primary" @click="exportExcelRequest"
        >导出 Excel</el-button
      >
    </div>
    <el-table
      ref="tableTreeRef"
      :data="bomInfos"
      style="width: 100%; margin-bottom: 20px"
      max-height="650px"
      row-key="child_item_revision_uid"
      :expand-row-keys="expand_row_keys"
      border
      lazy
      fit
      table-layout="auto"
      :load="loadChildrenBomInfo"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      v-loading="isDownloading"
      element-loading-text="文件生成中..."
    >
      <el-table-column
        show-overflow-tooltip
        prop="child_erp_id"
        label="编码"
        sortable
        width="200px"
      />
      <el-table-column
        show-overflow-tooltip
        prop="child_name"
        label="名称"
        sortable
        width="250px"
      >
        <template #default="{ row }">
          <div class="bom-table-first-col">
            <img :src="getIcon(row)" width="20px" height="20px" />
            {{ row.child_name }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="qty_value" label="数量" sortable />
      <el-table-column prop="procurementType" label="采购类型" sortable />
      <el-table-column
        prop="priceInfo.KEPH_USED"
        label="总成本"
        :formatter="formatter"
        sortable
      />
      <el-table-column
        prop="priceInfo.KEPH_SUM"
        label="单位成本"
        :formatter="formatter"
        sortable
      />
      <el-table-column
        prop="priceInfo.KEPH_KST001"
        label="材料成本"
        :formatter="formatter"
        sortable
      />
      <el-table-column
        prop="priceInfo.KEPH_MANUFACTURE"
        label="制造成本"
        :formatter="formatter"
        sortable
      />
      <el-table-column
        prop="priceInfo.KEPH_OTHER"
        label="其他成本"
        :formatter="formatter"
        sortable
      />
      <el-table-column
        prop="elapsedTime"
        label="工时"
        :formatter="formatter"
        sortable
      />
      <el-table-column
        show-overflow-tooltip
        prop="priceInfo.vendor_name"
        label="供应商"
        :formatter="formatter"
        sortable
        width="250px"
      />
    </el-table>
  </div>
  <div v-else>
    <el-empty :image-size="200" />
  </div>
</template>

<script setup>
import { nextTick, ref, defineProps, watch } from "vue";

let props = defineProps({
  uid: ref(),
  item: ref(),
  paneName: ref(),
  activeName: ref(),
});

const formatter = (row, column, cellValue) => {
  if (typeof cellValue === "number") {
    return cellValue.toFixed(2); // 保留小数点后两位
  } else {
    return cellValue; // 其他类型的数据原样返回
  }
};
</script>

<script>
import * as echarts from "echarts";
import elementResizeDetectorMaker from "element-resize-detector";
import XLSX from "xlsx";
// import { saveAs } from 'file-saver';
import FileSaver from "file-saver";
import { ElMessage } from "element-plus";
import { getIconByType } from "../vendor/TypeRendering.js";

export default {
  data() {
    return {
      isSearching: false,
      bomInfos: [],
      expand_row_keys: [],
      isDownloading: false,
    };
  },
  mounted: function () {
    //this.initPieChart("pieChart2");
    // 页面加载完成后调用初始化函数
    console.log("mounted");
    console.log("bomInfo => ", this.bomInfos);
    console.log("uid => ", this.uid);
    if (this.uid != null && this.uid.length > 0 && this.bomInfos.length == 0) {
      this.loadBomInfo();
    }
    this.$emit("setMultiSelect", false);
  },
  created() {
    watch(
      () => this.uid,
      (newUid, oldUid) => {
        console.log("uid =>", newUid, oldUid);
        this.loadBomInfo();
      }
    ),
      watch(
        () => this.activeName,
        (newName, curName) => {
          console.log("newName ==>" + newName);
          if (newName == this.paneName) {
            this.loadBomInfo();
          }
        }
      );
  },
  methods: {
    getIcon(item) {
      console.log(item);
      console.log(item.child_type);
      return getIconByType(item.child_type);
    },
    loadBomInfo() {
      console.log("查询价格信息");
      this.isSearching = true;
      const url = "/getBomInfo2?parentUid=" + this.uid;
      console.log(url);
      this.$http
        .get(url)
        .then((response) => {
          console.log("查询结果", response.data);
          // this.bomInfos = [response.data];
          // this.expand_row_keys = [this.bomInfos[0].child_item_revision_uid];
          this.bomInfos = response.data;
          this.isSearching = false;
        })
        .catch((error) => {
          this.isSearching = false;
          console.log(error);
        });
    },
    loadChildrenBomInfo(bomInfo, treeNode, resolve) {
      console.log("loadChildrenBomInfo", bomInfo, treeNode);
      console.log("child uid = ", bomInfo.child_item_revision_uid);
      const url = "/getBomInfo2?parentUid=" + bomInfo.child_item_revision_uid;
      console.log(url);
      this.$http
        .get(url)
        .then((response) => {
          console.log(response.data);
          resolve(response.data);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    exportExcelRequest() {
      const url = "/exportBomPrice?uid=" + this.uid;
      console.log(url);
      // this.$http
      //   .get(url)
      //   .then((response) => {
      //     console.log("查询结果", response.data);
      //     this.isSearching = false;
      //   })
      //   .catch((error) => {
      //     this.isSearching = false;
      //     console.log(error);
      //   });
      this.isDownloading = true;
      this.$http
        .get(url, {
          headers: {
            "Content-Type": "application/x-download",
          },
          responseType: "blob",
        })
        .then((response) => {
          this.isDownloading = false;
          let blob = new Blob([response.data], {
            type: "application/vnd.ms-excel",
          });
          let filename = "temp.xlsx";
          if (window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveBlob(blob, filename);
          } else {
            let aTag = document.createElement("a");
            aTag.download = "temp.xlsx";
            aTag.href = window.URL.createObjectURL(blob);
            aTag.click();
            URL.revokeObjectURL(aTag.href);
          }
        })
        .catch((error) => {
          console.log("文件下载失败", error);
          ElMessage.error("文件下载失败，" + error);
          this.isDownloading = false;
          // this.$message({
          //   type: "error",
          //   message: "文件下载失败",
          // });
          // this.downloading = false;
        });
    },
  },
};
</script>
<style>
.bom-table-first-col {
  display: flex;
  flex-direction: row;
  justify-content: start;
  align-items: center;
  gap: 5px;
}
</style>
